r
(< 500) 代表親戚數,跟著 r 個數字 S1 ... Sr
(< 30000)因為宣告是區域變數,所以用 Pass By Address 傳入
void bubble(int *s, int r);
void swap(int *a, int *b);
void min_distance(int *s, int r);
void sum(int *s, int r, int min);
while
迴圈逐次處理,每次分別先讀入親戚數 r
再用 for
迴圈讀入各親戚的門牌號,並存入整數陣列 s
(根據 r 的範圍,開 500 就夠;根據 s 的範圍,用 int 宣告),就可以開始瘋狂 call function 了
scanf("%d", &num);
while(num--){
int s[500] = {0}; //the street number
scanf("%d", &r);
for(i = 0; i < r; i++){
scanf("%d", &s[i]);
}
bubble(s, r);
}
void bubble(int *s, int r){
int i, j;
for(i = 0; i < r - 1; i++){
for(j = 0; j < r - 1 - i; j++){
if(s[j] > s[j + 1]){
swap(&s[j], &s[j + 1]);
}
}
}
min_distance(s, r); //find median
}
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
r
為奇偶數,分別求得中位數
r % 2 == 0
void min_distance(int *s, int r){
int min_d = 0;
if(r % 2 == 0){
min_d = (s[(r / 2) - 1] + s[(r / 2)]) / 2;
}
else{
min_d = s[(r / 2)];
}
sum(s, r, min_d);
}
void min_distance(int *s, int r){
sum(s, r, s[(r / 2)]);
}
for
迴圈取每個門牌和中位數的距離,這裡可用 abs
函式來取絕對值 (也可 if
判斷後大 - 小),每次更新總和 sum
,便可輸出最小距離和囉~
void sum(int *s, int r, int min){
int i;
int sum = 0;
for(i = 0; i < r; i++){
sum = sum + abs(min - s[i]);
}
printf("%d\n", sum);
}
#include<stdio.h>
void bubble(int *s, int r);
void swap(int *a, int *b);
void min_distance(int *s, int r);
void sum(int *s, int r, int min);
int main(){
int num; //number of test case
int r; //number of relatives
int i;
scanf("%d", &num);
while(num--){
int s[500] = {0}; //the street number
scanf("%d", &r);
for(i = 0; i < r; i++){
scanf("%d", &s[i]);
}
bubble(s, r);
}
return 0;
}
void bubble(int *s, int r){
int i, j;
for(i = 0; i < r - 1; i++){
for(j = 0; j < r - 1 - i; j++){
if(s[j] > s[j + 1]){
swap(&s[j], &s[j + 1]);
}
}
}
min_distance(s, r); //find median
}
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void min_distance(int *s, int r){
sum(s, r, s[(r / 2)]);
}
void sum(int *s, int r, int min){
int i;
int sum = 0;
for(i = 0; i < r; i++){
sum = sum + abs(min - s[i]);
}
printf("%d\n", sum);
}
vector
等 STL 來存門牌號sort
既方便也比泡沫排序快accumulate
加上 function,但此題感覺沒必要,就沒使用了#include <bits/stdc++.h>
using namespace std;
int main(){
int T; // number of test cases
int r; // number of relatives
int i, temp;
cin >> T;
while(T--){
vector<int> v;
int MID = 0;
int SUM = 0;
cin >> r;
for(i = 0; i < r; i++){
cin >> temp;
v.emplace_back(temp);
}
sort(v.begin(), v.end());
MID = v[r / 2];
for(i = 0; i < r; i++){
SUM = SUM + abs(MID - v[i]);
}
cout << SUM << endl;
}
return 0;
}